import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier


def calculate_knn_accuracy_and_plot(features, labels, dimension):
    """
    计算 KNN 分类准确率并绘制 10 次 10 折交叉验证的评分对比曲线

    :param features: 特征集
    :param labels: 标签集
    :return: 准确率
    """
    knn = KNeighborsClassifier(n_neighbors=5)
    # 绘制 10 次 10 折交叉验证的评分对比曲线
    scores = cross_val_score(knn, features, labels, cv=10)
    plt.figure(figsize=(10, 6))
    plt.plot(range(1, 11), scores, marker='o', linestyle='--')
    plt.title(f'Cross Validation Scores with {dimension} dimensions')
    plt.xlabel('Iteration')
    plt.ylabel('Accuracy')
    plt.grid(True)
    plt.show()
    return scores.mean()


if __name__ == '__main__':
    data = load_digits()
    features, labels = data.data, data.target
    # 64 维
    accuracy = calculate_knn_accuracy_and_plot(features, labels, 64)
    print("64维 准确率:", accuracy)
    # 10 维
    pca = PCA(n_components=10)
    reduced_features = pca.fit_transform(features)
    accuracy = calculate_knn_accuracy_and_plot(reduced_features, labels, 10)
    print("10维 准确率:", accuracy)
